package com.itheima.health.config;

import com.itheima.health.security.HealthUserDetailServiceImpl;
import com.itheima.health.security.JWTAuthenticationFilter;
import com.itheima.health.security.JWTAuthorizationFilter;
import com.itheima.health.security.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 *    重写默认配置类  WebSecurityConfigurerAdapter
 *    configure (AuthenticationManagerBuilder auth)   重写默认的用户认证信息 参照源码 注释编写
 *
 *    request.getParameter()    HttpxxxxWrapper   包装类   MvcWebConfigure  json null
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) //  开启权限注解
public class HealthWebSecurityConfiguration  extends WebSecurityConfigurerAdapter {

    @Autowired
    private HealthUserDetailServiceImpl healthUserDetailService;

    @Autowired
    JwtProperties properties;

    /**
     *  重写用户认证信息
     * @param auth
     * @throws Exception
     *
     * 密码加密 框架  PasswordEncoder  密码加密
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         //  数据库认证和授权配置
        auth.userDetailsService(healthUserDetailService).passwordEncoder(createPasswordEncoder());

//   内存版
//         auth.inMemoryAuthentication().passwordEncoder(createPasswordEncoder()).
//                 withUser("小明").password(createPasswordEncoder().encode("123")).roles("ADMIN").
//                 and().
//                 withUser("marry").password(createPasswordEncoder().encode("123")).roles("CHECKITEM_QUERY","CHECKGROUP_ADD","query");
//        System.err.println("============"+createPasswordEncoder().encode("123"));
    }

    /**
     * PasswordEncoder  对密码进行加密
     * @return
     */
    @Bean
    public PasswordEncoder  createPasswordEncoder(){
        return  new BCryptPasswordEncoder();
    }


    /**
     *   配置不需要认证的资源  浏览器直接可以访问
     */
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//             web.ignoring().antMatchers("/js/**","/css/**","/login.html");
//    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().
                disable(). // crsf   禁用
                 addFilter(new JWTAuthenticationFilter(super.authenticationManager(),properties))  // 启用 过滤器
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(),properties))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 禁用session


        //        http
//                .formLogin().loginPage("/login.html").//   定义自己的登录页面
//                loginProcessingUrl("/login.do"). //  重写 过滤器 UsernamePasswordAuthenticationFilter 处理 登录请求 地址
//                usernameParameter("name"). // 重写过滤器 解析表单的用户名 表单的name
//                passwordParameter("pwd").
//                defaultSuccessUrl("/pages/index.html",false).//  认证成功 跳转 页面//  认证失败  跳转 登录
//                failureUrl("/login.html").//  账号密码认证失败 跳转的页面
//                and()
//                .authorizeRequests().
//                antMatchers("/pages/delete.html").hasRole("ADMIN").  //   拥有 ADMIN角色 采用可以访问 delete.html
//                antMatchers("/pages/query.html").hasRole("query").
//                antMatchers("/pages/**").authenticated() //  只需要认证即可访问
//                .and().exceptionHandling().accessDeniedPage("/error.html")// 403 友好页面配置
//                .and().logout().logoutUrl("/logout.do").logoutSuccessUrl("/login.html").invalidateHttpSession(true)
//                .and().csrf().disable(); //  禁用 csrf  过滤器    token 令牌 校验
    }
}



